package com.tanhua.dubbo.mongo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.mongo.utils.TimeLineService;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;

import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;


import java.util.List;

@DubboService
public class MovementApiImpl implements MovementApi {

    @Autowired
    private MongoTemplate mongoTemplate;


    @Autowired
    private TimeLineService timeLineService;

    @Override
    public String save(Movement movement) {
        mongoTemplate.save(movement);

        Long userId = movement.getUserId();
        //根据用户id 查询好友列表
        timeLineService.saveTimeLine(userId, movement.getId());

        return movement.getId().toString();
    }


    //根据userId查询动态表中的数据
    public List<Movement> findById(Integer page, Integer pagesize, Long userId) {

        Criteria criteria = Criteria.where("userId").is(userId).and("state").is(1);
        Query query = Query.query(criteria).with(Sort.by(Sort.Order.desc("created")))
                .skip((page - 1) * pagesize).limit(pagesize);

        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        return movements;
    }

    //根据可见人id获得动态表中的数据
    public List<Movement> findByFriendId(Integer page, Integer pagesize, Long friendId) {

        //根据friendId查询 时间线表表中数据
        Criteria criteria = Criteria.where("friendId").is(friendId);
        Query query = Query.query(criteria)
                .with(Sort.by(Sort.Order.desc("created")))
                .skip((page-1)*pagesize).limit(pagesize);
        List<MovementTimeLine> timeLines = mongoTemplate.find(query, MovementTimeLine.class);

        //提取发布人的userIds
        List<Long> ids = CollUtil.getFieldValues(timeLines, "userId", Long.class);

        //根据ids获得动态表数据
        Criteria criteria1 = Criteria.where("userId").in(ids).and("state").is(1);
        Query query1 = Query.query(criteria1).with(Sort.by(Sort.Order.desc("created")));

        return mongoTemplate.find(query1,Movement.class);
    }

    //随机返回动态数据
    public List<Movement> findRandom(Integer pagesize) {
        //1.设计统计方法 ,
        TypedAggregation<Movement> aggregation = TypedAggregation.newAggregation(
                       Movement.class,
                       Aggregation.sample(pagesize));//采样方法

        //2,调用mongoTemplate方法进行数据统计,返回封装到result对象中
        AggregationResults<Movement> results = mongoTemplate.aggregate(aggregation, Movement.class);
        //3.提取统计结果
        List<Movement> movements = results.getMappedResults();

        return movements;
    }

    //根据MovementId返回动态数据
    public List<Movement> findByMovementIds(Integer page, Integer pagesize, String[] movementIds) {
        Criteria criteria = Criteria.where("id").in(movementIds);
        Query query = Query.query(criteria).with(Sort.by(Sort.Order.desc("created")))
                .skip((page - 1) * pagesize).limit(pagesize);

        List<Movement> movements = mongoTemplate.find(query, Movement.class);

        return movements;
    }

    //根据动态表的id查询单条动态
    public Movement findByMovementId(String id) {

        return mongoTemplate.findById(new ObjectId(id), Movement.class);
    }

    //根据照片状态码更新
    public void updateByState(String movementId, int state) {

        Query query = Query.query(Criteria.where("id").is(new ObjectId(movementId)));

        Update update=new Update();
        update.set("state",state);

        mongoTemplate.updateFirst(query,update,Movement.class);
    }


    //根据条件查询动态
    public PageResult findMovementList(Integer pagesize, Integer page, Long userId, Integer state) {
       Query query=new Query();

        if (userId!=null){
            query.addCriteria(Criteria.where("userId").is(userId));
        }

        if (state!=null){
            query.addCriteria(Criteria.where("state").is(state));
        }

        long count = mongoTemplate.count(query, Movement.class);

        query.with(Sort.by(Sort.Order.desc("created")))
                .skip((page-1)*pagesize)
                .limit(pagesize);

        List<Movement> movements = mongoTemplate.find(query, Movement.class);

        return new PageResult(page,pagesize,count,movements);
    }

    //查询动态表数据
    public List<Movement> selectByIds(String[] ids) {
        Criteria criteria = Criteria.where("id").in(ids);
        Query query = Query.query(criteria);
        return mongoTemplate.find(query,Movement.class);
    }

    //更新动态表数据
    public void updateState(String movementId, Integer state) {
        Query query = Query.query(Criteria.where("id").in(new ObjectId(movementId)));
        Update update =Update.update("state",state);
        mongoTemplate.updateFirst(query,update,Movement.class);
    }


}
